import { PropsWithChildren, useEffect } from "react";
import { SiderBar } from "../components/SiderBar";
import { useLegalAdviceStore } from "../store";
import { LegalAdviceChatInfo } from "./LegalAdvice/LegalAdviceChatInfo";
import { LegalAdviceIndex } from "./LegalAdvice/LegalAdviceIndex";
import {
  fetchCreateChat,
  fetchGetChatInfo,
} from "@/api/server/recommend_question";
import { sseRequest } from "@/api/sse";
import { AffixedChat } from "./LegalAdvice/AffixedChat";

interface ILegalAdviceProps {
  className?: string;
}

export function LegalAdvice(props: PropsWithChildren<ILegalAdviceProps>) {
  const list = useLegalAdviceStore((state) => state.list);
  const collapse = useLegalAdviceStore((state) => state.collapse);
  const activeKey = useLegalAdviceStore((state) => state.activeKey);
  const setActiveKey = useLegalAdviceStore((state) => state.setActiveKey);
  const setCollapse = useLegalAdviceStore((state) => state.setCollapse);
  const refreshList = useLegalAdviceStore((state) => state.refreshList);
  const listType = useLegalAdviceStore((state) => state.listType);
  const listSearch = useLegalAdviceStore((state) => state.listSearch);
  const setListType = useLegalAdviceStore((state) => state.setListType);
  const setListSearch = useLegalAdviceStore((state) => state.setListSearch);

  const onSubmit = async (str: string) => {
    const res = await fetchCreateChat({
      user_name: "test",
      sender: "user",
      message: str,
      type: "QA",
    });

    const chat_id = res.data.chat_id;
    refreshList();
    setActiveKey(chat_id, str);
    // console.log(res)

    // const res2 = await fetchGetChatInfo({
    //   chat_id: res.data.chat_id,
    //   search_type: 'chat_id',
    //   type: 'Law',
    // })

    // console.log(res2)
  };

  useEffect(() => {
    refreshList();
  }, []);

  return (
    <div className="flex flex-row h-full">
      <SiderBar
        type="legal-advice"
        setListSearch={setListSearch}
        setListType={setListType}
        listSearch={listSearch}
        listType={listType}
        list={list}
        collapse={collapse}
        onSetActiveKey={setActiveKey}
        onSetCollapse={setCollapse}
        refreshList={refreshList}
        activeKey={activeKey}
      />
      <div className="flex-1 min-w-0 PageContent flex flex-col items-center">
        <div className="w-[84%] h-full flex flex-col">
          {activeKey ? (
            <LegalAdviceChatInfo infoKey={activeKey} />
          ) : (
            <LegalAdviceIndex onSubmit={onSubmit} />
          )}
        </div>
      </div>
    </div>
  );
}
